import subprocess
import datetime
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(script_dir)


def run_command(command):
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return result.stdout.splitlines()

# 获取docker ps -a的输出
ps_command = "docker ps -a"
ps_output = run_command(ps_command)

# 获取docker images的输出
images_command = "docker images"
images_output = run_command(images_command)

# 将结果存入列表
docker_ps_list = ps_output
docker_images_list = images_output


container_line_data = []
for line in docker_ps_list:
    lines =line.split("   ")
    data = [x for x in lines if x != ""]
    container_line_data.append(data)

images_line_data = [] 
for line in docker_images_list:
    lines =line.split("   ")
    data = [x for x in lines if x != ""]
    images_line_data.append(data)
for data in container_line_data[1:]:
    container_id = data[0]
    container_image = data[1]
    image = data[1].split(":")[0]
    
    # 获取当前日期
    current_date_time = datetime.datetime.now()
    # 将当前日期格式化为所需的字符串形式
    date_time_string = current_date_time.strftime("%Y_%m%d_%H%M_%S")
    backup_cmd = f"docker commit {container_id} {image}:{date_time_string}"

    # 获取当前脚本文件的父目录
    sh_file_path = os.path.join(parent_dir, f"commit-{image.replace("/","_")}.sh")

    with open(sh_file_path, "w") as file:
        file.write("#!/bin/bash\n\n")
        # file.write("docker ps -a \n")
        file.write(backup_cmd + "\n")
        file.write(f"docker stop {container_id}\n")
        file.write(f"docker rm {container_id}\n")
        file.write(f"docker rmi {container_image}\n")
        # file.write("docker images \n")
    
    
    # print(backup_cmd)
    # print(f"docker stop {container_id}")
    # print(f"docker rm {container_id}")
    # print(f"docker rmi {container_image}")

